const Koa = require('koa')
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const index = require('./routes/index')
const wsRoute = require('./routes/ws')
let WebSocket = require("koa-websocket");
const app = WebSocket(new Koa())
// error handler
onerror(app)
app.use(async (ctx, next) => {
  ctx.set("Access-Control-Allow-Origin", "*")
  ctx.set("Access-Control-Allow-Headers", "*,access-token")
  ctx.set("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS,HEAD")
  // ctx.set("Access-Control-Allow-Credentials", true)
  ctx.set("X-Powered-By", "3.2.1")
  ctx.set("Content-Type", "application/json;charset=utf-8")
  if (ctx.method == 'OPTIONS') {   // 这句代码对跨域的处理非常重要
    ctx.response.status = 200;
    ctx.body = 200;
  } else {
    await next()
  }
})

// middlewares
app.use(bodyparser({
    enableTypes: ['json', 'form', 'text'],
    formLimit: "5mb",
    jsonLimit: "5mb",
    textLimit: "5mb"
}))
app.use(json())

// logger
app.use(async (ctx, next) => {
  await next();
})

// routes
app.use(index.routes(), index.allowedMethods())
app.use(index.routes(), index.allowedMethods())
app.ws.use(wsRoute.routes(), wsRoute.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
    console.error('server error', err, ctx)
});

module.exports = app
